import {
	createProductOrder,
	payProductOrder,
	queryProductOrderPayment,
	batchQueryProductOrderPayment,
	createMultiShopOrderAndPay,
	queryMultiShopOrderPayment
} from '@/api/productOrder.js';
import storage from '@/utils/storage.js';

/**
 * 商品订单支付处理类
 */
class ProductOrderPayment {
	constructor() {
		this.pollingIntervals = new Map(); // 存储轮询定时器
		this.maxPollingAttempts = 20; // 最大轮询次数
		this.pollingInterval = 3000; // 轮询间隔（毫秒）
	}

	/**
	 * 创建商品订单
	 * @param {Object} orderData 订单数据
	 */
	async createOrder(orderData) {
		try {
			const response = await createProductOrder(orderData);

			if (response.data.code === 200) {
				return response.data.data;
			} else {
				throw new Error(response.data.message || '创建订单失败');
			}
		} catch (error) {
			console.error('创建订单失败:', error);
			throw error;
		}
	}

	/**
	 * 发起支付
	 * @param {String} orderId 订单ID
	 * @param {String} openid 用户openid
	 */
	async initiatePayment(orderId, openid) {
		try {
			const response = await payProductOrder(orderId, openid);

			if (response.data.code === 200) {
				return response.data.data.wxPayParams;
			} else {
				throw new Error(response.data.message || '发起支付失败');
			}
		} catch (error) {
			console.error('发起支付失败:', error);
			throw error;
		}
	}

	/**
	 * 查询支付状态
	 * @param {String} orderId 订单ID
	 */
	async queryPaymentStatus(orderId) {
		try {
			const response = await queryProductOrderPayment(orderId);

			if (response.data.code === 200) {
				return response.data.data;
			} else {
				throw new Error(response.data.message || '查询支付状态失败');
			}
		} catch (error) {
			console.error('查询支付状态失败:', error);
			throw error;
		}
	}

	/**
	 * 批量查询支付状态
	 * @param {Array} orderIds 订单ID数组
	 */
	async batchQueryPaymentStatus(orderIds) {
		try {
			const response = await batchQueryProductOrderPayment(orderIds);

			if (response.data.code === 200) {
				return response.data.data;
			} else {
				throw new Error(response.data.message || '批量查询支付状态失败');
			}
		} catch (error) {
			console.error('批量查询支付状态失败:', error);
			throw error;
		}
	}

	/**
	 * 处理支付完成
	 * @param {String} orderId 订单ID
	 * @param {Function} onSuccess 成功回调
	 * @param {Function} onError 错误回调
	 * @param {Function} onTimeout 超时回调
	 */
	async handlePaymentComplete(orderId, onSuccess, onError, onTimeout) {
		try {
			// 1. 立即查询一次
			const immediateResult = await this.queryPaymentStatus(orderId);

			if (immediateResult.wechatTradeState === 'SUCCESS') {
				// 立即支付成功
				this.onPaymentSuccess(orderId, immediateResult);
				if (onSuccess) onSuccess(orderId, immediateResult);
				return;
			}

			// 2. 开始轮询查询
			this.startPolling(orderId, onSuccess, onError, onTimeout);

		} catch (error) {
			console.error('处理支付完成失败:', error);
			if (onError) onError(orderId, error);
		}
	}

	/**
	 * 开始轮询查询
	 * @param {String} orderId 订单ID
	 * @param {Function} onSuccess 成功回调
	 * @param {Function} onError 错误回调
	 * @param {Function} onTimeout 超时回调
	 */
	startPolling(orderId, onSuccess, onError, onTimeout) {
		let attempts = 0;

		const poll = async () => {
			try {
				const result = await this.queryPaymentStatus(orderId);

				if (result.wechatTradeState === 'SUCCESS') {
					// 支付成功
					this.stopPolling(orderId);
					this.onPaymentSuccess(orderId, result);
					if (onSuccess) onSuccess(orderId, result);
					return;
				} else if (result.wechatTradeState === 'CLOSED') {
					// 订单关闭
					this.stopPolling(orderId);
					this.onPaymentClosed(orderId, result);
					if (onError) onError(orderId, new Error('订单已关闭'));
					return;
				} else if (result.wechatTradeState === 'NOTPAY') {
					// 未支付，继续轮询
					attempts++;
					if (attempts < this.maxPollingAttempts) {
						this.pollingIntervals.set(orderId, setTimeout(poll, this.pollingInterval));
					} else {
						this.stopPolling(orderId);
						this.onPaymentTimeout(orderId);
						if (onTimeout) onTimeout(orderId);
					}
				}
			} catch (error) {
				console.error('轮询查询失败:', error);
				attempts++;
				if (attempts < this.maxPollingAttempts) {
					this.pollingIntervals.set(orderId, setTimeout(poll, this.pollingInterval));
				} else {
					this.stopPolling(orderId);
					if (onError) onError(orderId, error);
				}
			}
		};

		// 开始第一次轮询
		this.pollingIntervals.set(orderId, setTimeout(poll, this.pollingInterval));
	}

	/**
	 * 停止轮询
	 * @param {String} orderId 订单ID
	 */
	stopPolling(orderId) {
		const interval = this.pollingIntervals.get(orderId);
		if (interval) {
			clearTimeout(interval);
			this.pollingIntervals.delete(orderId);
			console.log('停止轮询:', orderId);
		}
	}

	/**
	 * 停止所有轮询
	 */
	stopAllPolling() {
		this.pollingIntervals.forEach((interval, orderId) => {
			this.stopPolling(orderId);
		});
		console.log('已停止所有商品订单轮询');
	}

	/**
	 * 检查是否有活跃的轮询
	 * @returns {boolean}
	 */
	hasActivePolling() {
		return this.pollingIntervals.size > 0;
	}

	/**
	 * 获取活跃轮询数量
	 * @returns {number}
	 */
	getActivePollingCount() {
		return this.pollingIntervals.size;
	}

	/**
	 * 支付成功回调
	 * @param {String} orderId 订单ID
	 * @param {Object} result 支付结果
	 */
	onPaymentSuccess(orderId, result) {
		console.log('支付成功！订单ID:', orderId, result);
		// 可以在这里添加成功提示、页面跳转等逻辑
	}

	/**
	 * 支付关闭回调
	 * @param {String} orderId 订单ID
	 * @param {Object} result 支付结果
	 */
	onPaymentClosed(orderId, result) {
		console.log('订单已关闭，订单ID:', orderId, result);
		// 可以在这里添加关闭提示等逻辑
	}

	/**
	 * 支付超时回调
	 * @param {String} orderId 订单ID
	 */
	onPaymentTimeout(orderId) {
		console.log('支付超时，订单ID:', orderId);
		// 可以在这里添加超时提示等逻辑
	}

	/**
	 * 获取用户openid
	 */
	getUserOpenid() {
		const userInfo = storage.getUserInfo();
		return userInfo?.openid || '';
	}

	/**
	 * 获取token
	 */
	getToken() {
		return storage.getAccessToken() || '';
	}

	/**
	 * 创建多店铺订单并支付
	 * @param {Object} multiShopOrderData 多店铺订单数据
	 */
	async createMultiShopOrderAndPay(multiShopOrderData) {
		try {
			const response = await createMultiShopOrderAndPay(multiShopOrderData);

			if (response.data.code === 200) {
				return response.data.data;
			} else {
				throw new Error(response.data.message || '创建多店铺订单失败');
			}
		} catch (error) {
			console.error('创建多店铺订单失败:', error);
			throw error;
		}
	}

	/**
	 * 查询多店铺订单支付状态
	 * @param {String} shopId 店铺ID
	 */
	async queryMultiShopOrderPayment(outTradeNo) {
		try {
			const response = await queryMultiShopOrderPayment(outTradeNo);

			if (response.data.code === 200) {
				return response.data.data;
			} else {
				throw new Error(response.data.message || '查询多店铺订单支付状态失败');
			}
		} catch (error) {
			console.error('查询多店铺订单支付状态失败:', error);
			throw error;
		}
	}
}

export default ProductOrderPayment;